import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class ChatServer {

	ArrayList streamSaidaClientes;

	public static void main(String[] args) {
		new ChatServer().go();

	}
	
	public void go(){
		streamSaidaClientes = new ArrayList();
		
		try {
			ServerSocket socketServidor = new ServerSocket(4240);
			while(true){
				Socket socketCliente = socketServidor.accept();
				PrintWriter writer = new PrintWriter(socketCliente.getOutputStream());
				streamSaidaClientes.add(writer);
				Thread tCliente = new Thread(new GerenciadorClientes(socketCliente));
				tCliente.start();
				
				System.out.println("Conectou");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void enviarParaTodos(String mensagem) {
		Iterator it = streamSaidaClientes.iterator();
		while(it.hasNext()){
			try {
				PrintWriter writer = (PrintWriter) it.next();
				writer.println(mensagem);
				writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	//Classe interna com o objeto runnable.
	public class GerenciadorClientes implements Runnable {
		BufferedReader reader;
		Socket socket;

		public GerenciadorClientes(Socket socketCliente) {
			try {
				socket = socketCliente;
				InputStreamReader estaLendo = new InputStreamReader(
						socket.getInputStream());
				reader = new BufferedReader(estaLendo);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		
		public void run(){
			String mensagem;
			try {
				while((mensagem= reader.readLine())!= null){
					String[] mensagens = mensagem.split(";", 2);
					String nomeCliente = mensagens[0];
					String mensagemExtraida = mensagens[1];
					System.out.println("Servidor recebeu mensagem: \"" + mensagemExtraida + "\" do cliente \"" + nomeCliente + "\".");
					enviarParaTodos(mensagem);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}

		
	}

}
